// src/preload.js
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
    // ==================== 通用 IPC ====================
    // 新增：允许渲染进程直接调用主进程的任意 handle
    invoke: (channel, ...args) => ipcRenderer.invoke(channel, ...args),

    // ==================== 案件管理 API ====================
    case: {
        getAll: () => ipcRenderer.invoke('get-cases'),
        getById: (id) => ipcRenderer.invoke('get-case-by-id', id),
        create: (caseData) => ipcRenderer.invoke('create-case', caseData),
        update: (updateData) => ipcRenderer.invoke('update-case', updateData),
        delete: (caseId) => ipcRenderer.invoke('delete-case', caseId),
        export: (caseId, formData) => ipcRenderer.invoke('export-case', caseId, formData),
        import: (filePath, formData) => ipcRenderer.invoke('import-case', filePath, formData),
    },

    // ==================== 数据操作 API ====================
    data: {
        import: (importData) => ipcRenderer.invoke('import-data-to-database', importData),
        get: (params) => ipcRenderer.invoke('get-case-data', params),
        export: (options) => ipcRenderer.invoke('export-data', options),
        delete: (options) => ipcRenderer.invoke('delete-case-data', options),
        clear: (params) => ipcRenderer.invoke('clear-case-data', params),
        clearImportLogs: (params) => ipcRenderer.invoke('clear-import-logs', params),
        query: (params) => ipcRenderer.invoke('execute-query', params),
    },

    // ==================== 文件选择 API ====================
    file: {
        selectExportPath: () => ipcRenderer.invoke('select-export-path'),

        // 更新：支持传递 options (如多选)
        selectImportFile: (options) => ipcRenderer.invoke('select-import-file', options),

        selectSaveFile: (options) => ipcRenderer.invoke('select-save-file', options),
        readText: (filePath) => ipcRenderer.invoke('read-text-file', filePath),

        // 更新：支持传递 options (如 sheetName)
        parse: (filePath, dataType, options) => ipcRenderer.invoke('parse-file', { filePath, dataType, options }),

        // 新增：专门暴露 inspect-files (虽然有了通用 invoke，但保留这个更规范)
        inspectFiles: (filePaths) => ipcRenderer.invoke('inspect-files', filePaths)
    },

    // ==================== 页面导航 API ====================
    navigation: {
        openWorkbench: (options) => ipcRenderer.send('open-workbench', options),
        goToMainPage: () => ipcRenderer.invoke('go-to-main-page'),
        onActivateTab: (callback) => {
            const subscription = (_event, data) => callback(data);
            ipcRenderer.on('activate-tab', subscription);
            // 返回清理函数
            return () => ipcRenderer.removeListener('activate-tab', subscription);
        },
        removeActivateTabListener: (callback) => {
            ipcRenderer.removeListener('activate-tab', callback);
        },
    },
});